const md5 = require('md5')

module.exports = {


  friendlyName: 'Register',


  description: 'Register user.',


  inputs: {
    loginName: {
      description: '登录名',
      type: 'string',
      required: true
    },
    password: {
      description: '用户密码',
      type: 'string',
      required: true
    },
    password0: {
      description: '确认密码',
      type: 'string',
      required: true
    },
    userName: {
      description: '姓名',
      type: 'string',
      required: true
    },
    gender: {
      description: '性别',
      type: 'string',
      required: true
    },
    birthDay: {
      description: '出生日期',
      type: 'string',
      required: true
    },
    career: {
      description: '职业',
      type: 'string',
      required: true
    }
  },


  exits: {

  },


  fn: async function (inputs) {
    try {
      await sails.getDatastore('mysql').transaction(async (db) => {
        var userMap = new Map()
        userMap.set('userName',inputs.userName)
        userMap.set('gender',inputs.gender)
        userMap.set('birthDay',inputs.birthDay)
        userMap.set('career',inputs.career)
        
        var newUser = await User.create(Object.fromEntries(userMap)).usingConnection(db).fetch()
  
        var userId = newUser.id
        var password = md5(inputs.password)
  
        var loginMap = new Map()
        loginMap.set('loginName',inputs.loginName)
        loginMap.set('password',password)
        loginMap.set('userId',userId)

        var newLogin = await Login.create(Object.fromEntries(loginMap)).usingConnection(db).fetch()

        var loginId = newLogin.id
        if(loginId == null || loginId == "" || loginId == undefined){
          this.res.send({'message':'fail'})
        }else{
          this.res.send({'message':'success'})
        }
      })
    } catch(error) {
      console.log(error)
      this.res.send({'message':'exception'})
    }
  }
};
